import logging

from flask import render_template, make_response, request
from flask_restful import Resource, reqparse
from app.commons.check_token import checkIfLogin
import urllib.parse

from app.commons.db import db
from app.commons.ma import ma
from app.commons.pagination import get_page
from app.models.buff_stock.buyer_stock import BuyerStockInfo
from app.service.csgo_stock.csgo_stock import GetTotalStock, GetBuyerStockWithRent, addRentForItem, deleteRentForItem, \
    deleteAllForItem, GetBuyerRentGrpByDateNd, get_total_info, GetBuyerRentGrpByMonth, addNewSkin
from enum import Enum

parser = reqparse.RequestParser(trim=True)


class StockRentReqType(Enum):
    AddRent = 1
    DeleteRent = 2
    DeleteAll = 3
    getRentChart = 4
    getTotalAsset = 5
    AddNewSkin = 6


class CsgoStockRentView(Resource):
    def post(self):
        try:
            cookie = urllib.parse.unquote(str(request.cookies.get('pj_login')))
            username = checkIfLogin(cookie)
            if username:
                recv_data = request.get_json()
                if recv_data["type"] == StockRentReqType.AddRent.value:
                    stock_id = recv_data["stock_id"]
                    rent_per_day = recv_data["rent_per_day"]
                    duration = recv_data["duration"]
                    rent = recv_data["rent"]
                    if rent == "" and rent_per_day != "" and duration != "":
                        rent = str(round(float(rent_per_day) * float(duration), 2))
                    item_id = recv_data["item_id"]
                    addRentForItem(username, stock_id, item_id, rent)
                elif recv_data["type"] == StockRentReqType.DeleteRent.value:
                    stock_id = recv_data["stock_id"]
                    deleteRentForItem(stock_id)
                elif recv_data["type"] == StockRentReqType.DeleteAll.value:
                    stock_id = recv_data["stock_id"]
                    deleteAllForItem(stock_id)
                elif recv_data["type"] == StockRentReqType.getRentChart.value:
                    data = GetBuyerRentGrpByDateNd(username, 30)
                    rent_by_month, total_buy_price = GetBuyerRentGrpByMonth(username)
                    data["date_month"] = list(rent_by_month.keys())
                    data["rent_by_month"] = list(rent_by_month.values())
                    try:
                        avg_rent = round(sum(data["rent_by_month"]) / len(data["rent_by_month"]), 2)
                    except ZeroDivisionError:
                        avg_rent = 0
                    data["avg_month"] = [avg_rent for i in range(len(data["rent_by_month"]))]
                    data["interest_by_month"] = [round(float(rent) * 12 / total_buy_price * 100, 2) for rent in
                                                 data["rent_by_month"]]
                    return {"success": "true", "err_msg": "", "data": data}
                elif recv_data["type"] == StockRentReqType.getTotalAsset.value:
                    data = get_total_info(username)
                    return {"success": "true", "err_msg": "", "data": data}
                elif recv_data["type"] == StockRentReqType.AddNewSkin.value:
                    skin_id = int(recv_data["skin_id"])
                    skin_name = recv_data["skin_name"]
                    price = recv_data["price"]
                    if skin_id and skin_name and price:
                        addNewSkin(skin_id, skin_name, price)
                    else:
                        return {"success": "false", "err_msg": "input error"}
                return {"success": "true"}
            else:
                return {"success": "false", "err_msg": "no login"}
        except:
            logging.warning("fail editing stockrentlist")
            return {"success": "false"}
